package com.itheima.youdianda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.youdianda.common.R;
import com.itheima.youdianda.dto.RegDto;
import com.itheima.youdianda.exception.CommonException;
import com.itheima.youdianda.mapper.YddUserMapper;
import com.itheima.youdianda.pojo.YddUserData;
import com.itheima.youdianda.pojo.YddUser;
import com.itheima.youdianda.service.UserService;
import com.itheima.youdianda.service.YddUserService;
import com.itheima.youdianda.utils.AppJwtUtil;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class YddUserServiceImpl extends ServiceImpl<YddUserMapper, YddUser>implements YddUserService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserService userService;

    @Override
    public R reg(Map<String, String> map) {
        String mobile = map.get("mobile");
        String password = map.get("password");

        LambdaQueryWrapper<YddUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YddUser::getMobile, mobile);
        List<YddUser> list = list(lqw);
        if (list != null && list.size() != 0){
            throw new CommonException("手机号已被注册");
        }
        YddUser yddUser = new YddUser();
        yddUser.setMobile(mobile);
        yddUser.setUsername(mobile);
        yddUser.setSex(0);
        yddUser.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        yddUser.setDefaultData("1");
        save(yddUser);

        LambdaQueryWrapper<YddUserData> userLqw = new LambdaQueryWrapper<>();
        userLqw.eq(YddUserData::getUserId, yddUser.getId());
        List<YddUserData> yddUserDataList = userService.list(userLqw);
        //封装dto
        RegDto regDto = new RegDto();
        regDto.setUserInfo(getOne(lqw));

        if (yddUserDataList == null || yddUserDataList.size() == 0){
            regDto.setArticleNum(0);
            regDto.setCollectNum(0);
            regDto.setZanNum(0);
            return R.success(regDto);
        }
        regDto.setArticleNum(yddUserDataList.size());
        userLqw.eq(YddUserData::getType, 1);
        List<YddUserData> collectList = userService.list(userLqw);
        regDto.setCollectNum(collectList.size());
        regDto.setZanNum(yddUserDataList.size() - collectList.size());
        //token
        String token = AppJwtUtil.getToken(yddUser.getId().toString());
        regDto.setToken(token);

        request.getSession().setAttribute("userId", yddUser.getId());

        return R.success(regDto);
    }
}
